﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Damany.RemoteImaging.Common;
using Damany.Util;
using DevComponents.DotNetBar.Keyboard;
using DevExpress.Data.Filtering;
using RemoteImaging.Extensions;
using DevExpress.XtraGrid.Columns;

namespace RemoteImaging.LicensePlate
{
    public partial class FormLicensePlateQuery : DevExpress.XtraEditors.XtraForm, ILicenseplateSearchScreen
    {
        private readonly ConfigurationManager _configurationManager;
        private readonly FileSystemStorage _videoRepository;
        private ILicensePlateSearchPresenter _presenter;
        private DateTime _lastFromTime;
        private DateTime _lastToTime;

        public FormLicensePlateQuery(ConfigurationManager configurationManager, FileSystemStorage videoRepository)
        {
            if (configurationManager == null) throw new ArgumentNullException("configurationManager");
            if (videoRepository == null) throw new ArgumentNullException("videoRepository");

            _configurationManager = configurationManager;
            _videoRepository = videoRepository;
            InitializeComponent();

            InitLicenseplateDataTable();

            var now = DateTime.Now;
            _lastToTime = now;
            _lastFromTime = now.AddHours(-1);

        }


        public bool IsBusy
        {
            set { this.UseWaitCursor = value; }
        }

        private void InitLicenseplateDataTable()
        {

            // licensePlateLists.DataSource = _licensePlates;
        }

        public void AttachPresenter(ILicensePlateSearchPresenter presenter)
        {
            if (presenter == null) throw new ArgumentNullException("presenter");

            _presenter = presenter;
        }

        public new void Show()
        {
            this.ShowDialog(Application.OpenForms[0]);
        }

        public void AddLicensePlateInfo(LicensePlateInfo licensePlateInfo)
        {

        }

        public void Clear()
        {
            if (InvokeRequired)
            {
                Action ac = this.Clear;

                this.BeginInvoke(ac);
                return;
            }

        }

        public bool MatchLicenseNumber
        {
            get
            {
                return false;
            }
            set { throw new NotImplementedException(); }
        }

        public string LicenseNumber
        {
            get { throw new NotImplementedException(); }// return (string)this.lpnToLookup.EditValue; }
            set { throw new NotImplementedException(); }
        }

        public bool MatchTimeRange
        {
            get { return false; }
            set { throw new NotImplementedException(); }
        }

        public DateTimeRange Range
        {
            get
            {
                //var range = new Damany.Util.DateTimeRange((DateTime) from.EditValue, (DateTime)to.EditValue);
                //return range;
                return null;
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        private void playRelatedVideo_Click(object sender, EventArgs e)
        {
            var row = GetSelectedPlateInfo();
            if (row == null) return;

            VideoPlayer.PlayRelatedVideo(row.CaptureTime, row.CaptureFrom);
        }

        private void licensePlateListView_CustomDrawEmptyForeground(object sender, DevExpress.XtraGrid.Views.Base.CustomDrawEventArgs e)
        {
            //var dataSource = licensePlateListView.DataSource;

            //var s = "未找到满足条件的车牌，请重新搜索";
            //var r = new Rectangle(e.Bounds.Left + 5, e.Bounds.Top + 5, e.Bounds.Width - 5,
            //                      e.Bounds.Height - 5);
            //e.Graphics.DrawString(s, e.Appearance.Font, e.Appearance.GetForeBrush(e.Cache), r);
        }


        private void UpcatePageIndicator()
        {
        }

        private void FormLicensePlateQuery_Load(object sender, EventArgs e)
        {
            gridControl1.Select();
            UpcatePageIndicator();
        }

        private void refreshButton_Click(object sender, EventArgs e)
        {
            //this.licensePlatesGridView.ApplyFindFilter((string)lpnToLookup.EditValue);
        }

        private void lpnToLookup_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                refreshButton_Click(null, null);
            }
            else if (e.KeyCode == Keys.Escape)
            {
                // lpnToLookup.EditValue = string.Empty;
            }
        }



        private void licensePlatesGridView_CustomFilterDialog(object sender, DevExpress.XtraGrid.Views.Grid.CustomFilterDialogEventArgs e)
        {
            if (e.Column.FieldName == "CaptureTime")
            {
                using (RemoteImaging.Controls.TimeRangeFilter filter = new Controls.TimeRangeFilter())
                {
                    filter.From = _lastFromTime;
                    filter.To = _lastToTime;
                    if (filter.ShowDialog(this) == DialogResult.OK)
                    {
                        e.FilterInfo =
                        new ColumnFilterInfo(ColumnFilterType.Custom,
                            null,
                            CriteriaOperator.Parse("CaptureTime >= ? and CaptureTime < ?", filter.From, filter.To),
                            null);

                        _lastFromTime = filter.From;
                        _lastToTime = filter.To;
                    };


                    e.Handled = true;
                }

            }
        }


        private void licensePlatesGridView_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            var row = this.licensePlatesGridView.GetRow(e.FocusedRowHandle) as DevExpress.Data.Async.Helpers.ReadonlyThreadSafeProxyForObjectFromAnotherThread;
            if (row != null && row.Content != null)
            {
                var lpi =  MapToLicensePlateInfo(row.Content);
                if (lpi != null)
                {
                    Image img = null;
                    if (!string.IsNullOrEmpty(lpi.ImagePath) && File.Exists(lpi.ImagePath))
                    {
                        try
                        {   
                            img = AForge.Imaging.Image.FromFile(lpi.ImagePath);
                        }
                        catch (Exception)
                        {
                            img = null;
                        }
                    }
                    
                    pictureEdit1.Image = img;
                    currentLicenseplateCaptureTime.EditValue = lpi.CaptureTime;
                    currentLicenseplateNumber.EditValue = lpi.LicenseplateNumber;
                }

            }
        }

        private DtoLicenseplateInfo GetSelectedPlateInfo()
        {
            var row = this.licensePlatesGridView.GetFocusedRow() as object[];
            return MapToLicensePlateInfo(row);
        }

        private DtoLicenseplateInfo MapToLicensePlateInfo(object[] row)
        {
            if (row == null) return null;
            if (row.Length < 5) return null;
            if (Array.TrueForAll<object>(row, o => o != null) == false) return null;

            var lpi = new DtoLicenseplateInfo
            {
                ImagePath = row[3] as string,
                CaptureFrom = (int)row[4],
                LicenseplateNumber = row[1] as string,
                CaptureTime = (DateTime)row[0]
            };

            return lpi;
        }

        private void licensePlatesGridView_CustomRowCellEdit(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e)
        {
            //if (e.RowHandle == DevExpress.XtraGrid.GridControl.AutoFilterRowHandle)
            //{
            //    if (e.Column.FieldName == "ThumbnailImage")
            //    {
            //        e.RepositoryItem = null;
            //    }
            //}
        }

    }

    internal class DtoLicenseplateInfo
    {
        public string ImagePath { get; set; }
        public string LicenseplateNumber { get; set; }
        public DateTime CaptureTime { get; set; }
        public int CaptureFrom { get; set; }

    }
}
